package com.netty.bfport.netty.server;

import com.netty.bfport.http.config.Thread.ThreadTaskPool;
import com.netty.bfport.http.config.Thread.WebMessagePushThread;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.concurrent.ScheduledFuture;

/**
 * @Author: zhaoyang
 * @Data: 2022/3/20 21:41
 * @Description
 * 任务调度类
 */

@Component
@Slf4j
public class WebTimeHandler  {

    //初始化时间
    @Value("${fzxy.cron}")
    public String cron;

    @Resource
    ThreadTaskPool threadTaskPool;

    /**
     * 外部调用定时任务，可通过此任务取消
     * @param cron cron表达式定时任务格式
     * */
    public void webMsgPushPub(String cron){
        this.cron = cron;
        webMsgPush();
    }

    /**
     * 启动时初始化定时任务，启动任务时会检查是否有任务执行，如果有，则停止任务，重新开启一个新任务
     * */
    @PostConstruct
    private void webMsgPush(){
        if (threadTaskPool.schedule!=null){
            //取消任务
            boolean cancel = threadTaskPool.schedule.cancel(false);
            // 查看任务是否在正常执行之前结束,正常true
            boolean cancelled = threadTaskPool.schedule.isCancelled();
            while (!cancelled) {
                threadTaskPool.schedule.cancel(true);
            }
        }
        threadTaskPool.schedule = threadTaskPool.scheduler.schedule(new WebMessagePushThread(cron), new CronTrigger(cron));

    }

    @PostConstruct
    public void asd(){
        System.out.println("post");
    }

    @PreDestroy
    public void weq(){
        System.out.println("pre");

    }

    public WebTimeHandler(){
        System.out.println("构造器");
    }





}
